package com.yx.cloud.network.ble.yx;

import com.yx.cloud.network.DataPacket;

import java.util.Arrays;

/**
 * 0帧头（Header）	1	固定为0xAA
 * 1顺序（Index）	1	从1开始，用于分包发送
 * 2数据总包数（PackageSum）	1	整体数据的分包总数
 * 3数据长度（Length）	1	数据包的有效长度：Cmd+Data
 * 4命令字（Cmd）	1	控制指令
 * 数据（Data）	N
 * 4+length 检校和（CheckSum）	1	Cmd和Data数据域的所有数据累加和
 */
public class YxBleDataPacket extends DataPacket {
    public static final byte HEADER = (byte) 0xAA;
    public static int SIZE = 20;
    public static int REAL_SIZE = 20 - 6;

    //包数据详情
    public byte header = (byte) 0xAA;
    public byte order;
    public byte packageSum;
    public byte length;
    public byte cmd;
    public byte[] data;
    public  byte checkSum;

    public YxBleDataPacket(byte[] packData) {
        this.packData = packData;

        this.header = packData[0];
        this.order = packData[1];
        this.packageSum = packData[2];
        this.length = packData[3];
        this.cmd = packData[4];
        this.data = new byte[length - 1];
        System.arraycopy(packData, 5, data, 0, data.length);
        this.checkSum = packData[0];
    }

    private static boolean checkData(byte[] packData) {
        int length = packData[3];
        byte checkSum = packData[4 + length];

        byte sum = 0;

        for (int i = 4; i < 4 + length; i++) {
            sum += packData[i];
        }

        return checkSum == sum;
    }

    public static boolean validateSlicePackage(byte[] packData) {
        if (packData == null || packData.length < 6 || packData[3] < 1 || packData.length < (4 + packData[3] + 1)) {
            //数据长度不对 抛弃
            return false;
        }

        if (packData[0] != (byte) 0xAA) {
            return false;
        }

        if (!checkData(packData)) {
            return false;
        }

        return true;
    }

    @Override
    public int getCmd() {
        return this.cmd;
    }

    @Override
    public int getOrder() {
        return this.order;
    }

    @Override
    public void setOrder(byte order) {
        this.order= order;
    }

    @Override
    public int getPacketSum() {
        return this.packageSum;
    }

    @Override
    public int getPacketLength() {
        return this.length;
    }

    @Override
    public byte[] getContentData() {
        return this.data;
    }


}
